<template>
  <div id="single-image-upload">
    <el-upload ref="upload"
               action=""
               accept=".jpg,.png"
               list-type="picture-card"
               :on-preview="handlePreview"
               :on-remove="handleRemove"
               :file-list="fileList"
               :http-request="handleHttpRequest"
               :limit="1">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogPreviewVisible" :modal="false">
      <img width="100%" :src="$fullUrl(value)" alt/>
    </el-dialog>
  </div>
</template>

<script>
console.log("UploadSingleImage.vue script")
import * as FileAPI from '@/api/file.js'

export default {
  name: "SingleImageUpload",
  props: {
    value: String
  },
  data() {
    return {
      dialogPreviewVisible: false,
      uploadBtn: undefined,
      fileList: [], //用于图片回显
    };
  },

  mounted() {
    //获取文件上传按钮的DOM元素，每个上传组件有且仅有1个
    this.uploadBtn = this.$refs.upload.$el.getElementsByClassName("el-upload")[0];
    this.handleValueChanged(this.value);

  },
  watch: {
    value(newValue) {
      this.handleValueChanged(newValue);
    }
  },

  methods: {
    handleValueChanged(value) {
      if (this.value) {
        this.fileList = [{
          url: this.$fullUrl(this.value)
        }]; //用于图片回显
        this.uploadBtn.style.display = "none";
      } else {
        this.fileList = []; //用于图片回显
        this.uploadBtn.style.display = "inline-block";
      }
    },

    handleHttpRequest(params) {
      // console.log(params)
      // 判断文件是否符合上传要求
      if (!this.beforeUpload(params.file)) {
        return;
      }

      let formData = new FormData();
      formData.append("file", params.file);
      formData.append("dir", "admin"); //指定云端upload下的存放目录
      //图片上传成功 result是接口返回数据{code message ,data{url,path}}
      FileAPI.uploadFile(formData).then(result => {
        if (result.code != 200) {
          this.$message.error("图片上传错误：" + result.message);
          return;
        }
        let imageUrl = result.data.url;
        this.fileList = [{
          url: this.$fullUrl(imageUrl)
        }];

        //不显示上传按钮
        this.uploadBtn.style.display = "none";
        //向父组件传递参数：imageUrl的值
        this.$emit("update:value", imageUrl);
      });
    },

    //移除图片
    handleRemove() {
      // 删除云端存储的文件
      let pathes = [];
      this.fileList.forEach(item => {
        pathes.push(item.url)
      })
      FileAPI.deleteFile(pathes).then(result => {
        console.log(result.message)
      }).catch(error => {
        console.log(error)
      })

      let imageUrl = "";
      this.fileList = [];

      //显示上传按钮
      this.uploadBtn.style.display = "inline-block";
      //向父组件传递参数：imageUrl的值
      this.$emit("update:value", imageUrl);
    },

    //文件上传之前调用做一些拦截限制
    beforeUpload(file) {
      const isJPGPNG = file.type === "image/jpg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPGPNG && isLt2M;
    },

    //预览图片时调用
    handlePreview() {
      this.dialogPreviewVisible = true;
    },
  },
};
</script>

<style lang="less" scoped>
</style>
